﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using gptDataType.Models;
using gptDataType.Type.combination;

namespace gptDataType.Helper
{
    public class FileInfo
    {
        //文件名
        public string FileName { get; set; } = string.Empty;
        //文件路径
        public string FilePath { get; set; } = string.Empty;
        public string FileType { get; set; } = string.Empty;
        public Sections_T Sections_T { get; set; } = new Sections_T();
        public List<StructuredText_T> STList { get; set; } = new List<StructuredText_T>();
        public List<FlgNet_T> LadList { get; set; } = new List<FlgNet_T>();
        public string ProgrammingLanguage { get; set; } = string.Empty;
        public string InstanceOfName { get; set; } = string.Empty;
        public PlcStruct? PlcStruct { get; set; }

    }
    public class ParseXmzXml
    {
        public string folderPath { get; set; } = string.Empty;
        public List<string> XmlFiles { get; set; } = new List<string>();
        //静态变量
        static readonly XNamespace ns_Interface = "http://www.siemens.com/automation/Openness/SW/Interface/v5";
        static readonly XNamespace ns_ST = "http://www.siemens.com/automation/Openness/SW/NetworkSource/StructuredText/v3";
        static readonly XNamespace ns_lad = "http://www.siemens.com/automation/Openness/SW/NetworkSource/FlgNet/v4";
        public List<FileInfo> fileInfos = new List<FileInfo>();  
        /// <summary>
        /// 获取所有xml文件
        /// </summary>
        /// <param name="folderPath">整体工程文件</param>

        public ParseXmzXml(string folderPath)
        {
            this.folderPath = folderPath;
            XmlFiles = GetXmlFiles();
        }
        /// <summary>
        /// 获取指定文件夹下的所有 .xml 文件的全路径列表
        /// </summary>
        /// <returns>包含所有 .xml 文件全路径的列表</returns>
        public List<string> GetXmlFiles()
        {
            // 检查文件夹是否存在
            if (!Directory.Exists(folderPath))
            {
                throw new DirectoryNotFoundException($"文件夹路径不存在：{folderPath}");
            }

            // 获取文件夹下所有 .json 文件的全路径
            string[] xmlFiles = Directory.GetFiles(folderPath, "*.xml", SearchOption.AllDirectories);

            // 将结果转换为 List<string> 并返回
            return new List<string>(xmlFiles);
        }
        public void ParseXmlFiles()
        {
            foreach (var file in XmlFiles)
            {
                try
                {
                    // 加载 XML 文件
                    XDocument document = XDocument.Load(file);

                    //解析文件名
                    FileInfo fileInfo = new();
                    XElement? Attr = null;
                    var instanceDB = document.Descendants("SW.Blocks.InstanceDB").FirstOrDefault();
                    var globalDB = document.Descendants("SW.Blocks.GlobalDB").FirstOrDefault();
                    var fB = document.Descendants("SW.Blocks.FB").FirstOrDefault();
                    var fC = document.Descendants("SW.Blocks.FC").FirstOrDefault();
                    var oB = document.Descendants("SW.Blocks.OB").FirstOrDefault();
                    var plcS = document.Descendants("SW.Types.PlcStruct").FirstOrDefault();
                    
                    if(instanceDB != null)
                    {
                        Attr = instanceDB.Element("AttributeList");
                        fileInfo.FileType="InstanceDB";
                    }
                    if(globalDB != null)
                    {
                        Attr = globalDB.Element("AttributeList");
                        fileInfo.FileType = "GlobalDB";
                    }
                    if(fB != null)
                    {
                        Attr = fB.Element("AttributeList");
                        fileInfo.FileType = "FB";
                    }
                    if(fC != null)
                    {
                        Attr = fC.Element("AttributeList");
                        fileInfo.FileType ="FC";
                    }
                    if(oB != null)
                    {
                        Attr = oB.Element("AttributeList");
                        fileInfo.FileType = "OB";
                    }
                    if(plcS != null)
                    {
                        Attr = plcS.Element("AttributeList");
                        fileInfo.FileType = "PlcStruct";
                    }
                    fileInfo.FileName = Path.GetFileNameWithoutExtension(file);
                    fileInfo.FilePath = file;
                    fileInfo.ProgrammingLanguage= Attr?.Element("ProgrammingLanguage")?.Value ?? string.Empty;
                    fileInfo.InstanceOfName = Attr?.Element("InstanceOfName")?.Value ?? string.Empty;
                    


                    // 使用 LINQ 查询定位 Sections 节点只有一个
                    var sectionsElement = document.Descendants(ns_Interface + "Sections").FirstOrDefault();

                    if (sectionsElement != null)
                    {
                        // 移除命名空间
                        XElement cleanedElement = RemoveNamespace(sectionsElement);

                        // 反序列化
                        Sections_T sections = DeserializeFromXElement<Sections_T>(cleanedElement);

                        // 调试输出具体内容
                        Debug.WriteLine($"Sections 节点解析成功，包含 {sections.Section.Length} 个 Section");
                        //foreach (var section in sections.Section)
                        //{
                        //    Debug.WriteLine($"Section Name: {section.Name}, Members Count: {section.Member.Length}");
                        //}
                        fileInfo.Sections_T = sections;
                    }
                    else
                    {
                        Debug.WriteLine( "没有找到任何 Sections 节点");
                    }

                    //定位st
                    var stElements = document.Descendants(ns_ST + "StructuredText").ToList();
                    if (stElements.Any())
                    {
                        var structuredTexts=new List<StructuredText_T>();

                        foreach (var stElement in stElements)
                        {
                            // 移除命名空间
                            XElement cleanedElement = RemoveNamespace(stElement);

                            // 反序列化
                            StructuredText_T structuredText = DeserializeFromXElement<StructuredText_T>(cleanedElement);
                            structuredTexts.Add(structuredText);
                        }
                        fileInfo.STList = structuredTexts;
                    }
                    else
                    {
                        Debug.WriteLine("没有找到任何 StructuredText 节点");
                    }
                    //定位lad
                    var ladElements = document.Descendants(ns_lad + "FlgNet").ToList();
                    if (ladElements.Any())
                    {
                        var flgNets = new List<FlgNet_T>();
                        foreach (var ladElement in ladElements)
                        {
                            // 移除命名空间
                            XElement cleanedElement = RemoveNamespace(ladElement);

                            // 反序列化
                            FlgNet_T flgNet = DeserializeFromXElement<FlgNet_T>(cleanedElement);
                            flgNets.Add(flgNet);
                        }

                        fileInfo.LadList = flgNets;
                    }
                    else
                    {
                        Debug.WriteLine("没有找到任何 FlgNet 节点");
                    }

                    fileInfos.Add(fileInfo);
                    Debug.WriteLine($"文件 {file} 解析成功");

                }
                catch (XmlException ex)
                {
                    Debug.WriteLine($"XML 解析错误: {ex.Message}");
                }
                catch (IOException ex)
                {
                    Debug.WriteLine($"文件读取错误: {ex.Message}");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"反序列化或其他错误: {ex.Message}");
                }
            }
        }
        /// <summary>
        /// 递归移除元素及其子元素的命名空间
        /// </summary>
        /// <param name="element">需要处理的 XElement</param>
        /// <returns>移除命名空间后的新 XElement</returns>
        private static XElement RemoveNamespace(XElement element)
        {
            return new XElement(
            element.Name.LocalName,
            element.Attributes().Where(a => !a.IsNamespaceDeclaration),
            element.Elements().Select(RemoveNamespace),
            element.HasElements ? null : element.Value);
        }
        /// <summary>
        /// 从 XElement 反序列化为指定类型的对象
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="element">XElement 实例</param>
        /// <returns>反序列化后的对象</returns>
        private static T DeserializeFromXElement<T>(XElement element)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StringReader reader = new StringReader(element.ToString()))
            {
                return (T)serializer.Deserialize(reader);
            }
        }
    }
}
